package org.praktika.api.service;

import lombok.RequiredArgsConstructor;


import org.modelmapper.ModelMapper;
import org.praktika.api.dto.PostDto;
import org.praktika.api.entity.Post;
import org.praktika.api.repository.PostRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class PostService {
    private final PostRepository postRepository;
    private final ModelMapper modelMapper = new ModelMapper();

    @Transactional
    public PostDto savePost(PostDto postDto) {
        Post post = modelMapper.map(postDto, Post.class);
        postRepository.save(post);
        return modelMapper.map(post, PostDto.class);
    }

    public PostDto getPostDtoById(Long id) {
        return modelMapper.map(getById(id), PostDto.class);
    }

    public Post getById(Long id) {
        Optional<Post> post = postRepository.findById(id);
        return post.orElseThrow(() -> new RuntimeException("No post found"));
    }


    @Transactional
    public PostDto updatePost(PostDto postDto) {
        Post post = getById(postDto.getId());
        post.setName(postDto.getName());
        postRepository.save(post);
        return modelMapper.map(post, PostDto.class);
    }

    public List<PostDto> findAllPost() {
        List<Post> posts = postRepository.findAll();
        List<PostDto> postDtos = new ArrayList<>();
        posts.forEach(post -> postDtos.add(modelMapper.map(post, PostDto.class)));
        return postDtos;
    }

    @Transactional
    public void deletePost(Long id) {
        postRepository.deleteById(id);
    }

}
